import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;

public class MyClient extends JFrame {
    private PrintWriter writer;
    Socket client_socket;
    private JTextArea send_area = new JTextArea();
    private JTextArea get_area = new JTextArea();
    private JTextField text = new JTextField();

    public MyClient() {
        setTitle("向服务器发送数据");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Container c = getContentPane();
        c.setLayout(new GridLayout(3,1));
        JScrollPane send_mes_scrollPane = new JScrollPane(send_area);
        c.add(send_mes_scrollPane, BorderLayout.NORTH);
        JScrollPane get_mes_scrollPane = new JScrollPane(get_area);
        c.add(get_mes_scrollPane, BorderLayout.CENTER);
        c.add(text, BorderLayout.SOUTH);
        text.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                writer.println(text.getText().trim());
                send_area.append(text.getText() + "\n");
                text.setText("");
            }
        });

    }

    private void connect() {
        send_area.append("消息发送页面:\n\n");
        send_area.append("尝试连接\n");
        try {
            client_socket = new Socket(InetAddress.getLocalHost(), 8998);
            writer = new PrintWriter(client_socket.getOutputStream(), true);
            send_area.append("完成连接\n"); 
            BufferedReader br = new BufferedReader(new InputStreamReader(
                    client_socket.getInputStream()));
            get_area.append("消息接收页面:\n\n");
            String s = null;
            while ((s = br.readLine()) != null) {
                get_area.append(s+"\n");
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    public static void main(String[] args) {
        MyClient client = new MyClient();
        client.setVisible(true);
        client.setSize(600, 700);
        client.connect();

    }

}
